//
//  HoCoreData.swift
//  pushfood
//
//  Created by HOA on 2020/12/25.
//

import Foundation
import CoreData

public enum HoCoreDataType {
    /// 本地
    case local
    /// 云端
    case cloud
}

public protocol HoCoreDataProtocol {
    
    static var mainContext: NSManagedObjectContext! { get }

    static func saveContext()
}

public struct HoCoreData: HoCoreDataProtocol {
    
    static public func saveContext() {
        guard mainContext.hasChanges else {
            return
        }
            
        do {
            try mainContext.save()
        }
        catch let nserror as NSError {
            fatalError("Unresolved error \(nserror),  \(nserror.userInfo)")
        }
    }
    
    private static var persistentContainer: NSPersistentContainer!
    
    public static var mainContext: NSManagedObjectContext! {
        get {
            persistentContainer?.viewContext
        }
    }
    
    init(_ name: String, _ type: HoCoreDataType = .local, _ beforeHandler: (() -> Swift.Void )? = nil) {
        
        if HoCoreData.persistentContainer != nil {
            return
        }
        
        var persistentContainer: NSPersistentContainer!
        if type == .local {
            persistentContainer = NSPersistentContainer(name: name)
        }
        else {
            if #available(iOS 13.0, *) {
                persistentContainer = NSPersistentCloudKitContainer(name: name)
            } else {
                fatalError("未适配iOS 13 以下云端数据库")
            }
        }
        
        persistentContainer?.loadPersistentStores { (desription, error) in
            if let error = error {
                fatalError("Unable to load persistentContainer stores: \(error)")
            }
            else {
                debugPrint("CoreData load success! \(desription)")
            }
        }
        HoCoreData.persistentContainer = persistentContainer
    }
    
    
}

extension HoCoreData {
    
    /**
     * CoreData 初始化
     *
     *  @param modelName 数据库文件名
     *  @type 数据库类型 云端 or 本地
     *  @handler 初始化数据库前回调函数
     */
    public static func configer(_ modelName: String,_ type: HoCoreDataType = .local, _ beforeHandler: (() -> Swift.Void )? = nil) {
        if mainContext == nil {
            _ = HoCoreData(modelName, type, beforeHandler)
        }
    }
}

